<?php

namespace app\api\controller;

use app\common\BaseHelper;
use app\admin\model\Meeting as MeetingMdl;
use app\admin\model\Joinmeeting;
use app\admin\model\Member;
use app\admin\model\Organization;
use app\admin\model\Institution;
use app\admin\model\Department;
use app\admin\service\Meeting as MeetingService;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 会议
 */
class Meeting extends BaseController
{

    /**
     * 获取会议列表
     *
     * @return \think\response\Json
     */
    public function getMeetingList()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'townId' => $param->townId
        ];
        if (isset($param->villageId) && $param->villageId) {
            $where['villageId'] = ['in', ['0', $param->villageId]];
        }
        $model = db('meeting');
        $fields = 'id, title, startTime, endTime, address, createOper, status';
        $result = $model->where($where)->field($fields)->order('startTime DESC')->limit($start, $length)->select();
        $total = $model->where($where)->count();

        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到会议');
        }

        foreach ($result as &$item){
            /*//$item->date = date('Y-m-d', strtotime($item->startTime));
            $item->date = date('Y-m-d', strtotime($item->startTime));
            //$item->startTime2 = substr($item->startTime, 11);
            $item->startTime2 = date('H:i', strtotime($item->startTime));
            $item->endTime2 = date('H:i', strtotime($item->endTime));*/
            // 发起人
            $publisher = Member::where(['id' => $item['createOper']])->value('name');
            if($publisher){
                $item['publisher'] = $publisher;
            }else{
                $item['publisher'] = $this->defaultOrganization;
            }
            unset($item['createOper']);
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 获取会议详情
     *
     * @return \think\response\Json
     */
    public function getMeetingDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->meetingId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'meetingId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }

        $meetingId = $param->meetingId;
        $where = [
            'townId' => $param->townId,
            'id' => $meetingId
        ];
        if (isset($param->villageId) && $param->villageId && $param->villageId != 'undefined') {
            $where = [
                'villageId' => $param->villageId
            ];
        }
        $fields = 'id, title, startTime, endTime, address, content, createOper, status';

        /*$item = MeetingMdl::where($where)->field($fields)->find();
        $item->date = date('Y-m-d', strtotime($item->startTime));
        $item->startTime2 = date('H:i', strtotime($item->startTime));
        $item->endTime2 = date('H:i', strtotime($item->endTime));*/
        $model = db('meeting');
        $item = $model->where($where)->field($fields)->find();

        if(empty($item)){
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关会议');
        }

        // 发起人
        $publisher = Member::where(['id' => $item['createOper']])->value('name');
        if($publisher){
            $item['publisher'] = $publisher;
        }else{
            $item['publisher'] = $this->defaultOrganization;
        }
        unset($item['createOper']);

        // 参会人员
        $join = [
            ['__MEMBER__ m', 'a.memberId = m.id'],
        ];
        $field = 'm.avatar, m.name';
        $joinmeeting = Joinmeeting::alias('a')->where(['meetingId' => $meetingId])->join($join)->field($field)->select();
        $item['joinmeeting'] = $joinmeeting;

        $userInfo = $this->getUserInfo(['id' => $param->userId]);
        $userJoinInfo = Joinmeeting::where(['memberId' => $userInfo['memberId']])->field('isConfirm, isSign')->find();
        // 是否已确认
        $item['isConfirm'] = $userJoinInfo['isConfirm'];
        // 是否已签到
        $item['isSign'] = $userJoinInfo['isSign'];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 获取成员
     */
    public function getMembers(){
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }

        $where = [
            'townId' => $param->townId
        ];
        if($param->type == 1){
            // 机构部门
            $institutionIds = Institution::where($where)->field('id')->select();
            $institutionIds = array_column($institutionIds, 'id');
            // 所有部门
            $model = new Department();
            $order = 'sorting ASC';
            $field = 'id, name';
            $result = $model->whereIn('institutionId', $institutionIds)->field($field)->order($order)->select();

            if (!$result) {
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关机构部门');
            }

            foreach ($result as $item) {
                // 部门下的成员
                $memberList = Member::where('departmentId', $item['id'])->field('id, name, avatar')->select();
                $item['memberList'] = $memberList;
            }
        }else{
            // 党组织
            // 所有组织
            $model = new Organization();
            $order = 'sorting ASC';
            $field = 'id, name';
            $result = $model->where($where)->field($field)->order($order)->select();

            if (!$result) {
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关党组织');
            }

            foreach ($result as $item) {
                // 组织下的成员
                $memberList = Member::where('organizationId', $item['id'])->field('id, name, avatar')->select();
                $item['memberList'] = $memberList;
            }
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }

    /**
     * 详情
     */
    public function detail(){
        $param = self::getHttpParam();
        $model = new MeetingMdl();

        if (empty($param->meetingId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'meetingId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }

        $meetingId = $param->meetingId;
        //$userInfo = $this->getUserInfo(['id' => $param->userId]);
        $where = [
            'id' => $meetingId,
            //'createOper' => $userInfo['memberId']
        ];
        $fields = '*';
        $item = $model->where($where)->field($fields)->find();

        if (empty($item)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关会议');
        }

        // 发起人
        $publisher = Member::where(['id' => $item['createOper']])->value('name');
        if($publisher){
            $item['publisher'] = $publisher;
        }else{
            $item['publisher'] = $this->defaultOrganization;
        }
        unset($item['createOper']);

        // 参会人员
        $join = [
            ['__MEMBER__ m', 'a.memberId = m.id'],
        ];
        $field = 'm.id, m.avatar, m.name, m.departmentId';
        $joinmeeting = Joinmeeting::alias('a')->where(['meetingId' => $meetingId])->join($join)->field($field)->select();
        foreach($joinmeeting as &$value){
            if($value['departmentId']){
                $value['bumen'] = 1;
            }else{
                $value['bumen'] = 2;
            }
        }
        $item['joinmeeting'] = $joinmeeting;

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 保存
     */
    public function save(){
        $param = self::getHttpParam();
        $model = new MeetingMdl();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->title)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'title 不能为空');
        }
        if (empty($param->date)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'date 不能为空');
        }
        if (empty($param->startTime)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'startTime 不能为空');
        }
        if (empty($param->endTime)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'endTime 不能为空');
        }
        if (empty($param->remind)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'remind 不能为空');
        }
        if (empty($param->address)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'address 不能为空');
        }
        if (empty($param->memberIds)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'memberIds 不能为空');
        }

        $userInfo = $this->getUserInfo(['id' => $param->userId]);
        $data = (array)$param;
        $area = $this->getParentIdsByTownId($data['townId']);
        $data['cityId'] = $area['cityId'];
        $data['xianId'] = $area['xianId'];
        $data['villageId'] = 0;
        $data['startTime'] = strtotime($data['startTime']);
        $data['endTime'] = strtotime($data['endTime']);

        Db::startTrans();
        try {
            if (!empty($param->meetingId)) {
                // 修改
                $data['id'] = $param->meetingId;
                $data['updateDate'] = time();
                $data['updateOper'] = $userInfo['memberId'];

                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
            } else {
                // 新增
                $data['id'] = BaseHelper::getUUID();
                $data['createDate'] = time();
                $data['createOper'] = $userInfo['memberId'];
                // 生成会议签到二维码
                $data['signCode'] = MeetingService::createMeetingCode($data['id'], $data['townId']);
                if(!$data['signCode']){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, '生成会议签到二维码失败！');
                }

                $result = $model->save($data);
            }

            if($result !== false){
                $memberIds = $param->memberIds;
                // 删除已经参加的人员
                Joinmeeting::where(['meetingId' => $data['id']])->delete();
                foreach ($memberIds as $id) {
                    $joinData = [
                        'id' => BaseHelper::getUUID(),
                        'createDate' => time(),
                        'meetingId' => $data['id'],
                        'memberId' => $id
                    ];
                    $res = Joinmeeting::insert($joinData);
                }
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, '添加参会人员失败');
                }

                Db::commit();
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '保存成功');
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, $e->getMessage());
        }
    }

    /**
     * 取消/删除
     */
    public function handle(){
        $param = self::getHttpParam();
        //$model = new MeetingMdl();

        if (empty($param->meetingId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'meetingId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }

        //$userId = $param->userId;
        $id = $param->meetingId;
        if($param->type == 1){
            // 取消
            $result = MeetingMdl::where('id', $id)->update(['status' => 2]);
            if($result === false){
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, '取消失败');
            }
        }else{
            // 删除
            Db::startTrans();
            $result = MeetingMdl::where('id', $id)->delete();
            if($result === false){
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除失败');
            }

            // 删除参会人员
            $res = db('joinmeeting')->where(['meetingId' => $id])->delete();
            if($res === false){
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除参会人员失败');
            }

            Db::commit();
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '操作成功');
    }

}